import redi_utils as utils
import redi_messages as please

feature_data_types = ["categorical", "continuous", "binary" ]
feature_usage = "\tredi %s import features -f /local/path/to/file.tsv -t %s"

def load(dataset_id, filename, config, options):
    dataType = utils.get_dataType(dataset_id, options, feature_usage, feature_data_types)

    itemid = options.id
    if itemid is None: itemid = utils.get_filename(filename)

    tablename = "FEATURES_%s_%s" % ( dataType.upper(), itemid )

    item_schema = []
    item_schema.append({ "name": "FEATURE_ID", "label": "Feature ID", "type": "string" })
    item_schema.append({ "name": "SAMPLE_ID", "label": "Sample ID", "type": "string" })

    if dataType == "categorical": item_schema.append({ "name": "VALUE", "label": "Value", "type": "string" })
    if dataType == "continuous": item_schema.append({ "name": "VALUE", "label": "Value", "type": "double" })
    # TODO: Figure out appropriate transformation here
    if dataType == "binary": item_schema.append({ "name": "VALUE", "label": "Value", "type": "binary" })

    outfile = open("%s/features/%s"%(dataset_id, tablename), "w")
    pivot_feature_data(filename, outfile, config)
    outfile.close()

    return { "id": itemid, "type": "features", "table": tablename, "schema": item_schema }

def pivot_feature_data(datafile, wfile, config):
    rfile = open(datafile)

    placeholder = "NA"
    if config.has_option("Globals", "missing.values.placeholder"):
        placeholder = config.get("Globals", "missing.values.placeholder")

    columnheaders = rfile.next()

    samplelist = columnheaders.rstrip().split("\t") # ignore first item, not a sample

    for line in rfile:
        contents = line.rstrip().split("\t")
        featureId = contents[0]
        for i, rawvalue in enumerate(contents):
            value = rawvalue
            if rawvalue == placeholder: value = "\N"
            if i > 0: wfile.write(featureId + "\t" + samplelist[i] + "\t" + value + "\n")
